﻿using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using AntDesign;
using Blazor.CoffeeTalesApi.Dto;
using Blazor.Core;
using Blazor.Core.Extensions;
using Blazor.Localization;
using Blazor.Pages.UpdateSetting.Modals.ChangeResourceUrl;
using Blazor.Pages.UpdateSetting.Modals.Whitelist;
using Blazor.ViewModels.UpdateSetting;
using DynamicData.Binding;
using Microsoft.Extensions.Localization;
using ReactiveUI;

namespace Blazor.Views.UpdateSetting;

public partial class SingleSetting : SoraniComponentBase<SingleSettingViewModel>
{
    private readonly IStringLocalizer<UpdateSettingLocalization> _loc;
    private readonly ModalService _modalService;

    public SingleSetting(IStringLocalizer<UpdateSettingLocalization> loc, ModalService modalService)
    {
        _loc = loc;
        _modalService = modalService;
    }

    protected override void BindWithViewModel(SingleSettingViewModel viewModel, CompositeDisposable disposable)
    {
        viewModel.NewWhitelistInteraction.RegisterHandler(NewWhitelistInteractionHandler).DisposeWith(disposable);
        viewModel.ChangeResourceUrlInteraction.RegisterHandler(ChangeResourceUrlInteractionHandler).DisposeWith(disposable);
        viewModel.ClearWhitelistInteraction.RegisterHandler(ClearWhitelistInteractionHandler).DisposeWith(disposable);

        viewModel.Whitelist.ObserveCollectionChanges().Subscribe(a =>
        {
            StateHasChanged();
        }).DisposeWith(disposable);
    }

    private async Task NewWhitelistInteractionHandler(IInteractionContext<Unit, WhitelistEntry?> context)
    {
        var setting = new WhitelistOptions()
        {
            Key = null,
            Raw = string.Empty,
            Default = string.Empty,
            Type = WhitelistOptions.EditType.All,
        };

        var result = await _modalService.OpenCustomModal<WhitelistModal, WhitelistOptions, WhitelistResult?>(setting);
        if (result is null)
        {
            context.SetOutput(null);
            return;
        }

        context.SetOutput(new WhitelistEntry()
        {
            Key = result.Value.Key,
            Value = result.Value.Entry,
        });
    }

    private async Task ChangeResourceUrlInteractionHandler(IInteractionContext<string, Uri?> context)
    {
        var result = await _modalService.OpenCustomModal<ChangeResourceUrlModal, string, Uri?>(context.Input);
        context.SetOutput(result);
    }

    private void ClearWhitelistInteractionHandler(IInteractionContext<Unit, bool> context)
    {
        context.SetOutput(true);
    }
}